package com.xilihui.xlh.business.activitys.store;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xilihui.xlh.R;
import com.xilihui.xlh.alipay.AuthResult;
import com.xilihui.xlh.alipay.PayResult;
import com.xilihui.xlh.business.activitys.TakeGoodsActivity;
import com.xilihui.xlh.business.adapters.BasePagerAdapter;
import com.xilihui.xlh.business.entities.PayEntity;
import com.xilihui.xlh.business.fragments.MyChecklistFragment;
import com.xilihui.xlh.business.fragments.StoreOrderFragment;
import com.xilihui.xlh.business.fragments.TakeGoodsFragment;
import com.xilihui.xlh.core.app.BaseCompatActivity;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.SPUtil;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;
import com.xyz.library.TabLayout;

import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/9/7.
 */

public class StoreOrderActivity extends BaseCompatActivity{
    
    @BindView(R.id.tablayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;

    public static String orderInfo = "";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    Intent intent;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.toastShortPositive("支付成功");
                        viewPager.setCurrentItem(2);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.toastShortNegative("支付失败");
                    }
//                    intent = new Intent(ConfirmListingActivity.this,MyChecklistActivity.class);
//                    intent.putExtra("wa_id",wa_id);
//                    intent.putExtra("agent_id",agent_id);
//                    startActivity(intent);
//                    YEventBuses.post(new YEventBuses.Event("pay"));
//                    finish();
                    break;
                }
                
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        ToastUtil.toastShortNegative("\"授权成功\\n\" + String.format(\"authCode:%s\", authResult.getAuthCode())");
                    } else {
                        // 其他状态值则为授权失败
                        ToastUtil.toastShortNegative("授权失败" + String.format("authCode:%s", authResult.getAuthCode()));
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    
    
    @Override
    public int getLayout() {
        return R.layout.activity_store_order;
    }

    @Override
    public String initTitle() {
        return "我的订单";
    }

    @Override
    public void initUI(@Nullable Bundle savedInstanceState) {
        viewPager.setOffscreenPageLimit(4);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                StoreOrderFragment storeOrderFragment = new StoreOrderFragment();
                Bundle bundle = new Bundle();
//                bundle.putString("wa_id",wa_id);
//                bundle.putString("agent_id",agent_id);
                int status = 0;
                switch (position){
                    case 0:
                        status = 10086;
                        break;
                    case 1:
                        status = 0;
                        break;
                    case 2:
                        status = 1;
                        break;
                    case 3:
                        status = 2;
                        break;
                    case 4:
                        status = 3;
                        break;
                }
                
                bundle.putInt("status",status);
                storeOrderFragment.setArguments(bundle);
                return storeOrderFragment;
            }
            
            @Override
            public int getCount() {
                return 5;
            }
            
        });

        tabLayout.setViewPager(viewPager);
    }

    @Override
    public void initData() {

    }
    
    public void getData(){
        
    }

    @Override
    public void onEventMainThread(YEventBuses.Event event) {
        super.onEventMainThread(event);
        if(event.is("store_pay")){
            String type = (String)event.getParams(0);
            if(type.equals("alipay")){
                orderInfo = (String) event.getParams(1);
                payV2(tabLayout);
            }else {
                PayEntity payEntity = (PayEntity)event.getParams(1);
                LogUtil.i("mylog","dddd"+payEntity.toString());
                weixiPay(payEntity);
            }
            
        }
    }

    /**
     * 支付宝支付业务
     *
     * @param v
     */
    public void payV2(View v) {
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);


//        /**
//         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
//         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
//         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险； 
//         *
//         * orderInfo的获取必须来自服务端；
//         */
//        boolean rsa2 = true;
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
//          
//        
//
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(StoreOrderActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    public void weixiPay(PayEntity payEntity){

        SPUtil.put(StoreOrderActivity.this,SPUtil.PAY_TYPE,2);
        IWXAPI msgApi = WXAPIFactory.createWXAPI(StoreOrderActivity.this,"wx086831d3499ea9c2", true);
        msgApi.registerApp("wx086831d3499ea9c2");

        boolean isWXAppInstalled = msgApi .isWXAppInstalled();
        if(isWXAppInstalled){
            PayReq request = new PayReq();
            request.appId = payEntity.getWeixin_payment_params().getAppid();
            request.partnerId = payEntity.getWeixin_payment_params().getPartnerid();
            request.prepayId= payEntity.getWeixin_payment_params().getPrepayid();
            request.packageValue = "Sign=WXPay";
            request.nonceStr= payEntity.getWeixin_payment_params().getNoncestr();
            request.timeStamp= payEntity.getWeixin_payment_params().getTimestamp()+"";
            request.sign= payEntity.getWeixin_payment_params().getSign();
            msgApi.sendReq(request);
        }else {
            ToastUtil.toastShortPositive("请先安装微信");
        }

    }
    
}
